@file:JvmMultifileClass
@file:JvmName("JsonKsl")

package hos.ksl

import org.json.JSONArray
import org.json.JSONObject

/**
 * <p>Title: JsonKsl </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-08-12 9:02
 * @version : 1.0
 */
fun JSONObject?.isNull(key: String): Boolean {
 if (this == null) {
  return true
 }
 try {
  val value = get(key)
  if (value is String) {
   return "null" == value ||
           "NULL" == value ||
           "Null" == value
  }
  if (value is JSONArray) {
   return value.length() == 0
  }
 } catch (_: Throwable) {
 }
 return true
}

fun JSONObject?.forEach(block: String.(Any?) -> Unit) {
 if (this == null) {
  return
 }
 keys().forEach {
  block.invoke(it, opt(it))
 }
}


fun JSONObject?.includes(item: Any): Boolean {
 if (this == null) {
  return false
 }
 try {
  keys().forEach {
   val value = opt(it)
   return value == item
  }
 } catch (_: Throwable) {
 }
 return false
}


fun JSONArray?.isNull(index: Int): Boolean {
 if (this == null) {
  return true
 }
 try {
  val value = get(index)
  if (value is String) {
   return "null" == value ||
           "NULL" == value ||
           "Null" == value
  }
  if (value is JSONArray) {
   return value.length() == 0
  }
 } catch (_: Throwable) {
 }
 return true
}

fun JSONArray?.forEach(block: Int.(Any?) -> Unit) {
 if (this == null || length() == 0) {
  return
 }
 val length = length()
 for (i in 0 until length) {
  block.invoke(i, opt(i))
 }
}